package com.andy.buyu.server.action;

import org.springframework.stereotype.Component;

import com.andy.buyu.server.game.GameUser;
import com.andy.buyu.server.game.Global;
import com.andy.buyu.server.game.Room;
import com.andy.buyu.server.socket.GmAction;
import com.andy.buyu.server.socket.MySocketSession;
import com.andy.buyu.server.socket.SendUtil;
import com.andy.buyu.server.socket.codec.DataWrap;
import com.andy.buyu.server.utils.GoConstant;

/**
 * 加入游戏逻辑
 * @author cuiwm
 *
 */
@Component(GmAction.ACTION_PREFIX+GmAction.ACTION_111)
public class Action111 implements IReqAction{

	@Override
	public void doAction(MySocketSession session, DataWrap data) {
		GameUser user = session.getUser();
		if(user.getGame() != null) return;
		int desk = data.getInt();
		int index = data.getByte();
		if(index < GoConstant.CHAIR_SIZE){
			// 加入房间
			Room room = Global.getRoom(desk);
			if(room == null) return;
			boolean isNew = false;
			synchronized (room) {
				if(!room.addUser(user,index)) {
					// 已经有人
					return;
				}
				isNew = room.enterGame(user);
			}
			SendUtil.send111(session, user); // 发送给当前玩家
			SendUtil.send112(user); // 通知其他玩家有人进入
			// 广播给大厅的人更新桌子信息
			SendUtil.send103(room, index);
			if(isNew) {
				// 开始游戏
				SendUtil.send205(room, room.getGame());
			}else {
				// 同步游戏状态
				SendUtil.send113(session, user);
			}
		}
		
	}


	
	
	
}
